"""


"""
from _warnings import filters

from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.response_code import RET
from . import index_blu

#　给当前蓝图创建和定义视图函数

@index_blu.route('/')
def index():
    # logging.fatal("致命错误")
    # logging.error("普通错误！")
    # logging.warning("警告错误！")
    # logging.info("普通日志信息！")
    # logging.debug("调试信息")
    title ="新经资讯网"
    user_id= session.get("user_id")
    user = None
    if user_id:
        # 根据user_id到数据库中查询用户信息
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 按点击排行
    news_clicks = []
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        # 　新闻分类列表
    categories = Category.query.all()
    # 新闻列表
    news_list = None
    total_page=0
    # 获取当前页码

    page = request.args.get('p', 1)
    try:
        paginate = News.query.order_by(News.id.desc()).paginate(int(page), constants.HOME_PAGE_MAX_NEWS, False)
#当前要显示的所有数据
        news_list = paginate.items  #总数据量
        total_page =paginate.pages  # 获取到总页数
        current_page = paginate.page  #
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    return render_template("news/index.html",
                           title =title,
                           user =user,
                           news_clicks = news_clicks,
                           categories = categories,
                           news_list = news_list,
                           total_page=total_page,
                           current_page=current_page
                           )

# 浏览器第一次访问网站的时候，会固定请求 /favicon.ico 获取网页小图标


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route("/news_list")
def news_list():
    """ajax请求新闻列表数据"""
    #1.接受参数，前端发送通过get参数发送
    data_dict = request.args
    page=data_dict.get("page",1) # 当前页码
    cid = data_dict.get("cid",1) #新闻分类ID
    per_page = data_dict.get("per_page",constants.HOME_PAGE_MAX_NEWS) #允许前端指定每一页数据
    try:
        page = int(page)
        per_page = int (per_page)
        cid = int(cid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg="参数错误")
    # 2.获取根据新闻分类获取新闻列表
    filter =[]
    if cid != 1:
        # 根据指定的分类ID来查询新闻列表
        filter.append(News.category_id==cid)
    try:
        paginate =News.query.filter(*filter).order_by(News.id.desc()).paginate(int(page),per_page,False)
        #获取查询出来的数据［items是一个列表，列表中的每一个成员都是模型对象］
        items = paginate.items
        # 获取到总页数
        tatal_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg="数据查询失败")
    #3.返回数据之前需要把每一个模型对象转换成字典格式，因为js不识别python的模型对象
    news_dict_list = []
    for news in items:
        news_dict_list.append(news.to_basic_dict())
    #4.返回结果
    return jsonify(errno=RET.OK,errmsg="OK",
                   totalPage = tatal_page,
                   currentPage = current_page,
                   newList= news_dict_list,
                   cid = cid
                   )
